package com.augurit.common.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.augurit.common.base.dao.BaseDao;
import com.augurit.common.entity.AcApplication;
import com.augurit.common.entity.AcServer;
import com.augurit.common.system.convert.AcServerConverter;
import com.augurit.common.system.util.OrgUtils;
import com.augurit.common.system.web.org.form.AcServerForm;

/**
 * WEB服务器DAO类
 */
@Repository
public class AcServerDao extends BaseDao<AcServer, Long> {

	@Autowired
	private AcApplicationDao acApplicationDao;
	
	@Autowired
	private AcMenuDao acMenuDao;
	
	public AcServerForm getForm(Long id){
		AcServerForm form = null;
		
		if(id != null){
			AcServer entity = this.get(id);
			if(entity != null)
				form = AcServerConverter.convertToForm(entity);
		}
		
		return form;
	}
	
	/**
	 * 保存WEB服务器Form对象
	 * @param form WEB服务器Form对象
	 */
	public void save(AcServerForm form){
		
		if(form != null){
			AcServer entity = null;
			
			//准备VO对象
			if(form != null && form.getServId() != null && form.getServId().intValue() > 0){
				entity = this.get(form.getServId());
			}else{
				form.setServId(null);
				entity = new AcServer();
			}
			
			//属性值转换
			AcServerConverter.convertToEntity(form, entity);
			
			//保存
			super.save(entity);
			
			//回填ID属性值
			form.setServId(entity.getServId());
		}
	}

	
	/**
	 * 保存WEB服务器Form对象
	 * @param form WEB服务器Form对象
	 */
	public void saveCascade(AcServerForm form){
		
		if(form != null){
			AcServer entity = null;
			
			//准备VO对象
			if(form != null && form.getServId() != null && form.getServId().intValue() > 0){
				entity = this.get(form.getServId());
			}else{
				form.setServId(null);
				entity = new AcServer();
			}
			
			//改变Web服务器的IP或端口后更新相关菜单链接地址
			changeServerIpOrPort(form, entity);
			
			//保存
			AcServerConverter.convertToEntity(form, entity);
			super.save(entity);
			form.setServId(entity.getServId());
		}
	}
	
	/**
	 * 改变Web服务器的IP或端口
	 * @param form
	 * @param entity
	 */
	public void changeServerIpOrPort(AcServerForm form, AcServer entity){
		if(form.getServId() != null && OrgUtils.isIpOrPortChange(form, entity)){
			Long[] appIds = acApplicationDao.getAppIdsByServId(form.getServId());
			if(appIds != null && appIds.length > 0){
				for(Long appId : appIds){
					
					//计算新的应用访问地址
					AcApplication acApplication = acApplicationDao.get(appId);
					String newAppUrl = OrgUtils.calcAppUrl(form, acApplication.getAppCode());
					
					//更新菜单链接地址
					acMenuDao.changeAppUrl(acApplication, newAppUrl);
					
					//更新应用
					acApplication.setAppUrl(newAppUrl);
					acApplicationDao.save(acApplication);
				}
			}
		}
	}
}
